<template>
  <div style="width:90%;">
    <el-form :model="planForm" :rules="planRules" ref="planForm" label-width="150px">
      <el-button @click="goback()" size="mini" type="primary" style="margin-left:1000px">返回</el-button>
      <el-input v-model="planForm.uuid" type="hidden"></el-input>
      <!-- <el-input v-model="planForm.orgSeq" type="hidden"></el-input> -->
      <el-form-item label="赠品类型" prop="giftType">
        <el-select v-model="planForm.giftType" :disabled="disabledFlagone">
          <el-option v-for="item in typeOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="赠品属性:" prop="giftProperty" v-if="planForm.giftType =='2'">
        <el-radio v-model="planForm.giftProperty" label="1" :disabled="disabledFlagone">普通虚拟赠品</el-radio>
        <el-radio v-model="planForm.giftProperty" label="2" :disabled="disabledFlagone">特殊虚拟赠品</el-radio>
      </el-form-item>
      <el-form-item label="礼品类型" prop="giftStyle" v-if="planForm.giftProperty =='2'">
        <el-select v-model="planForm.giftStyle">
          <el-option label="表情包" :value="8"></el-option>
          <el-option label="机场VIP" :value="4"></el-option>
          <el-option label="优惠券" :value="2"></el-option>
          <el-option label="现金优惠券" :value="7"></el-option>
          <el-option label="其他" :value="0"></el-option>
        </el-select>
        <!-- <el-radio v-model="planForm.giftStyle" :label="8">是</el-radio>
        <el-radio v-model="planForm.giftStyle" :label="0">否</el-radio> -->
      </el-form-item>
      <el-form-item label="赠品名称：" prop="giftName">
        <el-input v-model="planForm.giftName" :disabled="disabledFlag" style="width:360px;" placeholder="请输入奖品名称"
          maxlength="30" show-word-limit></el-input>
      </el-form-item>
      <el-form-item label="赠品描述：" prop="giftDesc">
        <el-input type="textarea" v-model="planForm.giftDesc" :disabled="disabledFlag" placeholder="请输入奖品说明"
          maxlength="120" show-word-limit :autosize="{minRows:2}" style="width:650px;"></el-input>
      </el-form-item>
      <el-form-item label="优惠券：" prop="planCouponList" v-if="planForm.giftType =='2'&&planForm.giftProperty=='1'">
        <el-table :data="planCouponList" @selection-change="planCouponChecked" border style="font-size: 10px;width:70%;"
          :header-cell-style="{background:'#eef1f6',color:'#606266'}">
          <el-table-column type="selection" width="55" align="center"></el-table-column>
          <el-table-column prop="couponName" label="优惠券名称" width="200" header-align="center"></el-table-column>
          <el-table-column prop="couponSeq" label="优惠券编号" width="150" header-align="center"></el-table-column>
          <el-table-column prop="couponMoney" label="优惠券面值" width="150" header-align="center" align="left">
            <template slot-scope="scope">
              <span>满{{scope.row.conponLimitMoney}}减{{scope.row.couponMoney}}元</span>
            </template>
          </el-table-column>
          <el-table-column prop="comments" label="使用说明" header-align="center"></el-table-column>
        </el-table>
        <div style="margin-top:10px;">
          <el-button type="primary" @click="selectCoupon('planForm')" v-if="!disabledFlag">选择卡券</el-button>
          <!-- <el-button @click="deleteCoupon('planForm')" v-if="!disabledFlag">删除卡券</el-button> -->
        </div>
      </el-form-item>

      <el-form-item label="赠品图片:" prop="imgListone">
        <image-upload v-model="planForm.imgListone" :size="'400x400'" :limit="1"></image-upload>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="submitForm('planForm')" v-if="!disabledFlag">保 存</el-button>
        <el-button @click="resetForm('planForm')">取 消</el-button>
      </el-form-item>
    </el-form>

    <el-dialog title="选择优惠券" :visible.sync="dialogVisibleCoupon" width="55%">
      <el-form :inline="true" :model="formCoupon" class="search-form-inline" style="margin-top:-20px;">
        <el-input v-model="formCoupon.couponName" style="width:200px;" placeholder="优惠券名称"></el-input>
        <el-button type="primary" size="mini" icon="el-icon-search" @click="getCouponList()">查询</el-button>
      </el-form>
      <el-table ref="singleTable" :data="couponList" @selection-change="couponChecked" border
        style="font-size: 10px;width:100%;" height="300" :header-cell-style="{background:'#eef1f6',color:'#606266'}">
        <el-table-column type="selection" width="55" align="center"></el-table-column>
        <el-table-column prop="couponName" label="优惠券名称" width="200" header-align="center"></el-table-column>
        <el-table-column prop="couponSeq" label="优惠券编号" width="150" header-align="center"></el-table-column>
        <el-table-column prop="couponMoney" label="优惠券面值" width="150" header-align="center">
          <template slot-scope="scope">
            <span>满{{scope.row.conponLimitMoney}}减{{scope.row.couponMoney}}元</span>
          </template>
        </el-table-column>
        <el-table-column prop="comments" label="使用说明" header-align="center"></el-table-column>
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisibleCoupon = false">取 消</el-button>
        <el-button type="primary" @click="couponConfirm()" :disabled="this.lsCouponList.length!=1">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
  import {
    addPrize,
    updatePrize,
    queryGenCoupon
  } from "@/api/prizeLibrary";
  import {
    queryPromotionList,
    queryPromotionById,
    queryCouponById,
    savePromotion,
    updatePromotionStatus,
    createTPlan
  } from "@/api/promotionProgramEdit";
  import imageUpload from "@/page/common/Image-upload";
  import {
    queryCouponList
  } from "@/api/promotionProgramEdit";
  import {
    editGiftBank
  } from "@/api/giftbank";
  export default {
    data() {
      return {
        keepAlive: true,
        logininfo: {},
        orgList: [],
        //   orgSeq: "",
        loading: true,
        typeOptions: [{
            value: "2",
            label: '虚拟赠品'
          },
          {
            value: "1",
            label: '实物赠品'
          }
        ],
        lsPlanCouponList: [],
        lsCouponList: [],
        planCouponList: [],
        couponList: [],
        planForm: {
          uuid: "",
          giftType: "2",
          giftProperty: "1",
          giftName: "",
          giftDesc: "",
          giftStyle: 0,
          // beginTime: "",
          // endTime: "",
          status: "",
          promotionCouponInfo: [],
          imgListone: [],
          giftPic: "",
          couponId: ""
        },
        formCoupon: {
          couponName: ""
        },
        dialogVisibleCoupon: false,
        disabledFlag: false,
        disabledFlagone: true,
        listQuery: {
          current: 1,
          size: 10
        },
        total: 0,
        planRules: {
          giftType: [{
            required: true,
            message: "请选择赠品类型",
            trigger: "blur"
          }],
          giftName: [{
            required: true,
            message: "请输入赠品名称",
            trigger: "blur"
          }],
          giftDesc: [{
            required: true,
            message: "请输入赠品描述",
            trigger: "blur"
          }],
          imgListone: [{
            required: true,
            message: "",
            trigger: "blur"
          }]


        }
      };
    },
    components: {
      imageUpload
    },
    mounted() {
      this.logininfo = localStorage.getItem("logininfo");
      this.orgList = JSON.parse(this.logininfo).orgList;
      // this.orgSeq = this.orgList[0].orgSeq;
      // this.planForm.orgSeq = this.orgList[0].orgSeq;
      this.disabledFlag = this.$route.params.disabledFlag
      this.disabledFlagone = this.$route.params.disabledFlagone
      var v = this.$route.params.edit;
      if (v) {
        // 修改，回显值
        this.planForm.uuid = v.uuid;
        this.planForm.giftName = v.giftName;
        this.planForm.giftType = String(v.giftType);
        this.planForm.giftProperty = String(v.giftProperty);
        this.planForm.giftPic = v.giftPic;
        this.planForm.couponId = v.couponId;
        // this.planCouponList = res.result.promotionCouponInfo;
        this.planForm.imgListone = v.giftPic == null || v.giftPic == "" ? [] : [v.giftPic];
        this.planForm.giftDesc = v.giftDesc;
        if (this.planForm.giftProperty == '2') {
          this.planForm.giftStyle = v.giftStyle
        }
        //   this.planForm.beginTime = v.beginTime;
        //   this.planForm.endTime = v.endTime;
        this.planForm.status = v.status;

        this.queryPromotionById(v.couponId);
      } else {
        // 新增，默认值
        this.planForm.uuid = "";
        this.planForm.status = "1";
        this.getCouponList();
      }
    },
    methods: {
      goback() {
        this.$router.go("-1");
      },
      quantityBlur(e, idx) {
        if (e.target.value == '') {
          return;
        }
        let flag = new RegExp("^[1-9][0-9]*$").test(e.target.value);
        if (!flag) {
          this.$message({
            message: "限领数量请输入正整数",
            type: "warning"
          });
          e.target.value = '';
        }
      },
      numberBlur(e, name) {
        if (e.target.value == "") {
          return;
        }
        let flag = new RegExp("^[1-9][0-9]*$").test(e.target.value);
        if (!flag) {
          this.$message({
            message: name + "请输入正整数",
            type: "warning"
          });
          e.target.value = "";
        }
      },
      queryPromotionById(uuid) {
        let data = {
          size: 100,
          current: 1,
          condition: {},
          ascs: [],
          descs: []
        };
        queryGenCoupon(data).then(res => {
          if (
            res.records != null &&
            res.records.length > 0
          ) {
            // this.planCouponList =res.records;
            // 去掉已选的
            for (var i in res.records) {
              console.log(uuid);
              console.log(res.records[i]);
              if (uuid == res.records[i].uuid) {
                this.planCouponList.push(res.records[i]);
              }
            }

          }
          this.getCouponList();
        });
        this.loading = false;
      },

      getCouponList() {
        let data = {
          size: 100,
          current: 1,
          condition: {
            status: 1,
            couponType: 1,
            keyWord: this.formCoupon.couponName
          },
          ascs: [],
          descs: []
        };
        queryGenCoupon(data).then(res => {
          this.couponList = res.records;
          // 去掉已选的
          // for (var i in this.planCouponList) {
          //   this.removeByValue(
          //     this.couponList,
          //     "uuid",
          //     this.planCouponList[i].uuid
          //   );
          // }
        });
        this.loading = false;
      },

      planCouponChecked(row) {
        this.lsPlanCouponList = row;
      },
      couponChecked(row) {
        this.lsCouponList = row;
        if (this.lsCouponList.length > 1) {
          this.$refs.singleTable.toggleRowSelection(this.lsCouponList[0]);
        }
      },
      selectCoupon() {
        // 显示选择卡券对话框
        this.dialogVisibleCoupon = !this.dialogVisibleCoupon;
      },
      deleteCoupon() {
        // 删除已选择的卡券
        this.couponList = this.couponList.concat(this.lsPlanCouponList);
        for (var i in this.lsPlanCouponList) {
          this.removeByValue(
            this.planCouponList,
            "uuid",
            this.lsPlanCouponList[i].uuid
          );
        }
      },
      couponConfirm() {
        this.dialogVisibleCoupon = !this.dialogVisibleCoupon;
        this.planCouponList = this.lsCouponList; //this.planCouponList.concat(this.lsCouponList);
        // for (var i in this.lsCouponList) {
        //   this.removeByValue(this.couponList, "uuid", this.lsCouponList[i].uuid);
        // }
      },

      submitForm(formName) {
        // 保存奖品
        //   if (this.planForm.prizeType == "2"){
        if (this.planForm.giftName == "" || this.planForm.giftName == null) {
          this.$message.error("请输入赠品名称");
          return;
          //   }
        }
        if (this.planForm.giftDesc == "" || this.planForm.giftDesc == null) {
          this.$message.error("请输入赠品描述");
          return;
          //   }
        }
        if (this.planForm.giftType == "2" && this.planCouponList.length == 0 && this.planForm.giftProperty == "1") {
          this.$message.error("请选择一张卡券");
          return;
        }
        if (this.planForm.imgListone.length == 0) {
          this.$message.error("请上传图片");
          return;
        }

        for (var i in this.planCouponList) {
          // 删除提交时不需要的属性或容易导致错误的属性
          if (
            this.planCouponList[i].couponId != null &&
            this.planCouponList[i].couponId != undefined
          ) {
            this.planCouponList[i].couponId = this.planCouponList[i].uuid;
          }
          delete this.planCouponList[i].createTime;
          delete this.planCouponList[i].createUser;
          delete this.planCouponList[i].updateTime;
          delete this.planCouponList[i].updateUser;
          // delete this.planCouponList[i].beginTime;
          // delete this.planCouponList[i].endTime;
          delete this.planCouponList[i].comments;
          delete this.planCouponList[i].validCreateDate;
          delete this.planCouponList[i].validEndDate;
        }
        this.planForm.promotionCouponInfo = this.planCouponList;
        if (this.planForm.giftType == "2" && this.planForm.giftProperty == "1") {
          this.planForm.couponId = this.planForm.promotionCouponInfo[0].uuid;
          this.planForm.prizeName = this.planForm.promotionCouponInfo[0].couponName;
        }

        this.planForm.giftPic = this.planForm.imgListone[0]

        const data = {
          ...this.planForm
        }

        this.keepAlive = false;
        console.log(this.planForm);
        if (this.planForm.uuid == "") {
          this.planForm.uuid = null
          editGiftBank(data).then(res => {
            if (res.code == "1") {
              this.$message({
                showClose: true,
                message: "保存成功",
                type: "success"
              });
              //   this.$router.push("prizeLibrary");
              this.$router.push("giftbank");
            } else {
              this.$message({
                showClose: true,
                message: "保存失败",
                type: "success"
              });
            }
          });
        } else {
          editGiftBank(data).then(res => {
            if (res.code == "1") {
              this.$message({
                showClose: true,
                message: "修改成功",
                type: "success"
              });
              //   this.$router.push("prizeLibrary");
              this.$router.push("giftbank");
            } else {
              this.$message({
                showClose: true,
                message: "修改失败",
                type: "success"
              });
            }
          });
        }
      },
      // 数组，属性，属性值
      removeByValue: function(arr, attr, value) {
        if (arr == null) {
          return;
        }
        var index = 0;
        for (var i in arr) {
          if (arr[i][attr] == value) {
            index = i;
            break;
          }
        }
        arr.splice(index, 1);
      },
      handleRemove(file, fileList) {
        let newfileList = [];
        fileList.forEach((item, i) => {
          let data = {
            name: item.name,
            url: item.url
          };
          newfileList.push(data);
        });
        this.fileList = newfileList;
      },
      resetForm(formName) {
        this.$refs[formName].resetFields();
        this.$router.push("giftbank");
      }
    },
    beforeRouteLeave(to, from, next) {
       
      // 设置下一个路由的 meta
      to.meta.keepAlive = this.keepAlive; // C 跳转到 A 时让 A 不缓存，即刷新
      next();
    },
  };
</script>
<style lang="less" scoped>
  .el-col-20 {
    border: 1px solid #ebeef5;
    margin-left: 150px;
    width: 60%;
  }

  .el-input {
    width: 60%;
  }

  .search-form-inline {
    border: 1px solid #ebeef5;
    line-height: 30px;
    padding: 12px;
    margin-bottom: 5px;
  }

  thead {
    .el-table-column--selection {
      .cell {
        display: none;
      }
    }
  }
</style>
